package com.ultimatech.wxservice.web.controller;

import com.ultimatech.webappdemo.authmgr.service.IAuthService;
import com.ultimatech.webappdemo.authmgr.service.IPasswordService;
import com.ultimatech.webappdemo.base.model.SysUser;
import org.apache.shiro.authc.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

/**
 * Created by 张乐平 on 7/28 0028.
 */
@Controller
@RequestMapping("/authc")
public class AuthcController extends MainsiteErrorController {

    private Logger logger = LoggerFactory.getLogger(AuthcController.class);

    @Autowired
    private IAuthService authService;

    public IAuthService getAuthService() {
        return authService;
    }

    public void setAuthService(IAuthService authService) {
        this.authService = authService;
    }

    @Autowired
    private IPasswordService passwordService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@Valid SysUser user, @RequestParam(value = "rememberMe", required = false) String rememberMe, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        logger.info("用户:" + user.getUsername() + "请求登录");
        try {
            if (bindingResult.hasErrors()) {
                redirectAttributes.addFlashAttribute("user", user);
                redirectAttributes.addFlashAttribute("username", user.getUsername());
                return "redirect:/login";
            }
            boolean r = Boolean.valueOf(rememberMe == null ? false : true);
            //使用权限工具进行用户登录，登录成功后跳到shiro配置的successUrl中，与下面的return没什么关系！
            this.getAuthService().logIn(user.getUsername(), passwordService.encrypt(user.getPassword()), r);
            return "redirect:/main";
        } catch (AuthenticationException e) {
            redirectAttributes.addFlashAttribute("message", "用户名或密码错误");
            redirectAttributes.addFlashAttribute("username", user.getUsername());
            return "redirect:/login";
        }
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(RedirectAttributes redirectAttributes) {
        //使用权限管理工具进行用户的退出，跳出登录，给出提示信息
        this.getAuthService().logOut();
        redirectAttributes.addFlashAttribute("message", "您已安全退出");
        return "redirect:/login";
    }

    @RequestMapping("/403")
    public String unauthorizedRole() {
        return "403";
    }
}
